package pers.kw.config.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Arrays;

/**
 * OAuth配置
 */
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired
    public AuthorizationServerConfig(
            AuthenticationManager authenticationManager,
            MyAuthenticationEntryPoint myAuthenticationEntryPoint,
            PasswordEncoder passwordEncoder,
            UserDetailsService userDetailsService) {
        this.passwordEncoder = passwordEncoder;
        this.myAuthenticationEntryPoint = myAuthenticationEntryPoint;
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 授权服务安全认证配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证客户端信息
        //在自定义客户端异常处理过滤器时，不能开启这个，否则会导致过滤器失效，仍使用原来的
        //security.allowFormAuthenticationForClients();

        //自定义客户端异常处理过滤器
        MyClientCredentialsTokenEndpointFilter myClientCredentialsTokenEndpointFilter =
                new MyClientCredentialsTokenEndpointFilter(security);
        myClientCredentialsTokenEndpointFilter.afterPropertiesSet();
        myClientCredentialsTokenEndpointFilter.setAuthenticationEntryPoint(myAuthenticationEntryPoint);
        security.addTokenEndpointAuthenticationFilter(myClientCredentialsTokenEndpointFilter);
    }

    /**
     * 客户端信息配置
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("ec")
                .secret(passwordEncoder.encode("ec"))

                //配置授权服务支持的授权模式
                .authorizedGrantTypes("refresh_token", "authorization_code")
                //令牌允许获取的资源权限
                .scopes("all").autoApprove(true)
                .redirectUris("https://blog.csdn.net/qq_36762765");
    }

    /**
     * 授权服务端点配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //刷新token需要
        endpoints.userDetailsService(userDetailsService);

        //认证管理器
        endpoints.authenticationManager(authenticationManager);

        //自定义异常信息返回值（授权码模式、密码模式）
        endpoints.exceptionTranslator(new MyWebResponseExceptionTranslator());

        //设置token请求方式
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST);

        //token存储方式
        endpoints.tokenStore(tokenStore());
        endpoints.accessTokenConverter(jwtAccessTokenConverter());

        //token增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        endpoints.tokenEnhancer(tokenEnhancerChain);

        //增加自定义请求参数，spring security5.3开始用如下方法
        //当前依赖是5.2版本，不能这么写
        //endpoints.addEndpointFilter(filter);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //这是对称加密方式
        jwtAccessTokenConverter.setSigningKey("kw");
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }
}
